/**
 * 
 */
package com.metagurukul.metaspace.actions;

import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.metagurukul.metaspace.controller.WorkDetailsForm;
import com.metagurukul.metaspace.models.beans.UserProject;
import com.metagurukul.metaspace.models.beans.UserWorkDetail;
import com.metagurukul.metaspace.service.UserService;

/**
 * @author bhagyesh
 * 
 */
public class WorkDetailsAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws SQLException {
		HttpSession session = request.getSession(true);
		com.metagurukul.metaspace.controller.WorkDetailsForm workForm = (WorkDetailsForm) form;
		int userId = (Integer) session.getAttribute("id");
		int department = workForm.getDepartment();
		int project = workForm.getProject();
		int role = workForm.getRole();
		if (insertWorkDetail(userId, department, project,
				role)) {
			return mapping.findForward("success");
		} else {
			ActionMessages errors = new ActionMessages();
			errors.add("error", new ActionMessage("error.workDetails.notInsert"));
			saveErrors(request, errors);
			return mapping.getInputForward();
		}
	}

	private boolean insertWorkDetail(int userId, int departmentId, int projectId,
			int roleId) throws SQLException {
		UserWorkDetail userWorkDetail = new UserWorkDetail();
		userWorkDetail.setUserId(userId);
		userWorkDetail.setDeptId(departmentId);
		userWorkDetail.setRoleId(roleId);
		ArrayList<UserProject> userProjectList = new ArrayList<UserProject>();
		UserProject userProject = new UserProject();
		userProject.setUserId(userId);
		userProject.setProjectId(projectId);
		userProjectList.add(userProject);
		userWorkDetail.setUserProjectList(userProjectList);
		return UserService.insertWorkDetail(userWorkDetail);
	}
	
	
}
